What is the trim() method in jQuery? Explain it with the help of an example?
trim() method in jQuery
228
28-Jul-2021
Aryan Kumar
14-Jun-2023The jQuery trim() method is used to remove whitespace from the beginning and end of a string. It is a chainable method, which means that you can call other jQuery methods on the returned object.
The trim() method takes no arguments.
Here is an example of how to use the trim() method:
Code snippet
The trim() method can also be used to remove whitespace from the beginning and end of an attribute value. For example, the following code will remove the whitespace from the beginning and end of the href attribute value of the element with the id 'my-element':
Code snippet
The trim() method is a useful tool for removing whitespace from strings and attribute values. It can be used to improve the readability of your code and to make sure that your code is consistent.
Here are some additional examples of how the trim() method can be used:
// Trim the whitespace from the beginning and end of the value of the input element with the id 'my-input' $('#my-input').val().trim();
// Trim the whitespace from the beginning and end of the text content of all elements with the class 'my-class' $('.my-class').text().trim();